import * as region from	'@/static/data/regions.json'
import {
	ref,computed
}from 'vue'

const useArea = (cb) =>{
	const areaPicker = ref();
	const provinces =ref([]);//省
	const citys =ref([]);//市
	const areas =ref([]);//区
	const pickerValue =ref([0, 0, 0]);
	const defaultValue =ref([3442, 1, 2]);		
	const prevIndex = ref(0)
	provinces.value = region.default.sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1));
	
	const addressList = computed(() => {
		return [provinces.value, citys.value, areas.value];
	})
	
	

	handlePickValueDefault()
	
	function handlePickValueDefault() {
			// 设置省
			pickerValue.value[0] = provinces.value.findIndex(item => Number(item.id) === defaultValue.value[0]);
			// 设置市
			citys.value = provinces.value[pickerValue.value[0]]?.children || [];
			pickerValue.value[1] = citys.value.findIndex(item => Number(item.id) === defaultValue.value[1]);
			// 设置区
			areas.value = citys.value[pickerValue.value[1]]?.children || [];
			pickerValue.value[2] = areas.value.findIndex(item => Number(item.id) === defaultValue.value[2]);
			// 重置下位置
			areaPicker.value?.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]],true);
		}
	    function areaChange(e) {
			const { columnIndex, index} = e
			// 改变了省
			if (columnIndex === 0) {
				prevIndex.value = index;
				citys.value = provinces.value[index]?.children || []
				areas.value = citys.value[0]?.children || []
				areaPicker.value?.setIndexs([index, 0, 0])
			} else if (columnIndex === 1) {
				areas.value = citys.value[index]?.children || []
				areaPicker.value.setIndexs([prevIndexs.value,index,0])
			}
		}
		
		function open() {
			areaPicker.value.open();
			handlePickValueDefault()
		}
		
		function areaConfirm(e) {
			console.log('确认选择的地区：', e);
				//广东省-广州市-番禺区
				let str = []
				e.value.forEach(item =>{
					str.push(item.name)
				})
				cb(str.join('-'))
		}
		return [areaPicker,addressList,areaChange,areaConfirm,open]
	}
	

export default useArea;
